package middleware

import (
	"context"
	"errors"
	"fmt"
	"net/http"
	"net/url"

	"github.com/gin-gonic/gin"
	"gorm.io/gorm"

	"awesomeProject/app/model"
	"awesomeProject/app/response"
	"awesomeProject/global"
)

// Authorize 校验token有效性
func Authorize() gin.HandlerFunc {
	return func(ctx *gin.Context) {
		var url *url.URL = ctx.Request.URL
		//fmt.Println(url)
		global.LoggerOut(url)

		token := ctx.Request.Header.Get("token")
		if token == "" {
			ctx.JSON(http.StatusUnauthorized, response.ErrUnAuthorize)
			ctx.Abort()
			return
		}
		cacheKey := fmt.Sprintf("fordeal:user:token:%s", token)
		var userCache model.UserCache
		if err := global.RedisClient.HGetAll(context.Background(), cacheKey).Scan(&userCache); err != nil {
			ctx.JSON(http.StatusUnauthorized, response.ErrSystem)
			ctx.Abort()
			return
		}
		if userCache.UUID == "" || userCache.ID <= 0 {
			ctx.JSON(http.StatusUnauthorized, response.ErrInvalidToken)
			ctx.Abort()
			return
		}
		// 设置上下文
		var user model.User
		err := global.Gorm.Where("`id` = ? AND `status` = ?", userCache.ID, 1).First(&user).Error
		if err != nil {
			if errors.Is(err, gorm.ErrRecordNotFound) {
				ctx.JSON(http.StatusUnauthorized, response.ErrRecordNotFound.SetMsg("用户不存在或已禁用"))
			} else {
				ctx.JSON(http.StatusUnauthorized, response.ErrSystem)
			}
			ctx.Abort()
			return
		}
		user.SuperAdmin = user.ID == global.SuperAdminUserID
		ctx.Set("user", user)
		//global.LoggerOut(userCache.ID)
		ctx.Next()
	}
}
